package model

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"os"
)

type User struct {
	Id       int
	UserName string
	Password string
}

func getDataSource() *sql.DB {
	db, err := sql.Open("mysql", "root:root@/threetest?charset=utf8")
	checkError(err)
	checkError(db.Ping())
	return db
}

func AddUser(user User) (row int64) {
	db := getDataSource()
	defer db.Close()

	statement, err := db.Prepare("insert into user(username, password) values(?,?)")
	checkError(err)
	res, err := statement.Exec(user.UserName, user.Password)
	checkError(err)
	row, err = res.RowsAffected()
	checkError(err)

	return
}

func UpdateUser() {

}

func DelUserById() {

}

func FindUserById() {

}

func FindUserByName() {

}

func CheckUser(user User) bool {
	db := getDataSource()

	defer db.Close()
	sql := "select * from user where username=? and password = ?"
	rows, err := db.Query(sql, user.UserName, user.Password)
	checkError(err)
	return rows.Next()
}

func checkError(err error) {
	if err != nil {
		fmt.Println("error :", err)
		os.Exit(1)
	}
}
